package com.example.mysecondprojecct.test.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

import com.example.mysecondprojecct.common.Data;
import com.example.mysecondprojecct.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("/get")
    public String demo(){
        return "nnnn";
    }
    @CrossOrigin
    @PostMapping(value = "/upload/{type}/{detail}")
    public Result<?> upload(@RequestPart(value = "file", required = false) MultipartFile file,
                            @PathVariable String type,
                            @PathVariable String detail) throws IOException {

        System.out.println("上传文件...");
        if (file == null)
            return Result.faile("文件为空");

        String originalFilename = file.getOriginalFilename();//获取源文件的名称
        String flag = IdUtil.fastSimpleUUID();//定义唯一标识
        String rootFilePath = "";
        rootFilePath = System.getProperty("user.dir") + "/files/" + type + "/" + detail + "/" + flag + originalFilename;

        File rootFile = new File(rootFilePath);
        if (!rootFile.getParentFile().exists()) {
            rootFile.getParentFile().mkdirs();
        }

        FileUtil.writeBytes(file.getBytes(), rootFilePath);

        return Result.success(Data.ip + "/file/getFile/" + type + "/" + detail + "/" + flag + originalFilename);  // 返回结果 url
    }

    @GetMapping("/getFile/{type}/{detail}/{flag}")
    public void getFiles(@PathVariable String flag, @PathVariable String type, @PathVariable String detail,
                         HttpServletRequest request,
                         HttpServletResponse response) {


        String fileName = System.getProperty("user.dir") + "/files/" + type + "/" + detail + "/" + flag;   //获取视频
        try {
            if (StrUtil.isNotEmpty(fileName)) {
//                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                Path filePath = Paths.get(fileName);
                String mimeType = Files.probeContentType(filePath);

                if (!mimeType.equals("")) {
                    response.setContentType(mimeType);
                }

//                response.setContentType("application/octet-stream");
                if (mimeType.equals("video/mp4")) {
                    File file = new File(fileName);

                    String rangeString = request.getHeader("Range");
                    long range = Long.parseLong(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    response.setContentLength(Math.toIntExact(file.length()));
                    response.setHeader("Content-Range", String.valueOf(range + (file.length() - 1)));
                    response.setHeader("Accept-Ranges", "bytes");

                }


                byte[] bytes = FileUtil.readBytes(fileName);  // 通过文件的路径读取文件字节流
                OutputStream os = response.getOutputStream();   // 通过输出流返回文件


                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println(e + "getfile");
        }
    }
//    @GetMapping("/getfile/vedio/{detail}/{flag}")
//    public void getPreview2( @PathVariable String flag,@PathVariable String detail,HttpServletResponse response) {
//        try {
//
//            String fileName = System.getProperty("user.dir") +"/files/"+"vedio"+"/"+detail+"/"+flag;   //获取视频
//            File file = new File(fileName);
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            response.setHeader("Content-Disposition", "attachment; filename="+file.getName().replace(" ", "_"));
//            InputStream iStream = new FileInputStream(file);
//            IOUtils.copy(iStream, response.getOutputStream());
//            response.flushBuffer();
//
//        } catch (java.nio.file.NoSuchFileException e) {
//            response.setStatus(HttpStatus.NOT_FOUND.value());
//        } catch (Exception e) {
//            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//        }
//    }


}



